package mplayer.dao;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.annotations.QueryBinder;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import mplayer.entity.User;

public class UserDao {
	
	Long resultsCount;
	
	public List<User> getUsers(Integer maxResults,Integer firstResult,User user) {
		List<User> list ;
		Session session = HibernateUtil.getSessionFactory().openSession();

		Criteria cr = session.createCriteria(User.class);

		if(user != null){
			if (user.getId() != null) {
				cr.add(Restrictions.eq("id", user.getId()));
			}
			if (user.getLogin() != null) {
				cr.add(Restrictions.like("login", "%"+user.getLogin()+"%"));				
			}
		}
		
		resultsCount = (Long) cr.setProjection(Projections.rowCount()).uniqueResult();
		cr.setMaxResults(maxResults);
		cr.setFirstResult(firstResult);
		// Remove count projection
		cr.setProjection(null);
		list = cr.list();		

		session.close();		
		return (List<User>)list;
	}

	public void addUser(User user) {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		session.save(user);
		tx.commit();
		session.close();

	}
	
	public void delteUserBuId(Integer id) {
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		User user = new User();
		user.setId(id);
		session.delete(user);
		tx.commit();
		session.close();
	}

	public User updateUser(User user){
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		session.update(user);
		tx.commit();
		session.close();
		
		return user;
	}

	public Long getResultsCount() {	
		return resultsCount;
	}

	public void setResultsCount(Long resultsCount) {
		
		this.resultsCount = resultsCount;
	}
    
	

	public List<User>  getUserByLoginPw(String userid, String password) {
	    List<User> list ;
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		
		String hql = "from User U WHERE U.login='"+userid+"'  AND U.password='"+password+"'";
		Query query = session.createQuery(hql);
		
		list = query.list();
		
		tx.commit();
		session.close();		
		
		
		return list;  
	}


	
}
